/*
 *  Jiki - a small lightweight wiki engine.
 *
 *  Copyright 2008 Peter Halbmayer <phalbmayer@gmail.com
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

package at.pmsa.jiki.util;

import java.io.FileNotFoundException;
import java.util.Enumeration;
import java.util.Hashtable;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DBHelper {

    private static final String DATABASE_TABLE = "jikicont";
    
    private static final String DATABASE_CREATE ="create table " +
    	DATABASE_TABLE + " (title text not null, body text not null);";

    private static final String DATABASE_NAME = "jiki";

    private static final int DATABASE_VERSION = 1;

    private SQLiteDatabase db;

    public DBHelper(Context ctx){
        try{
            db = ctx.openDatabase(DATABASE_NAME, null);
        }
        catch(FileNotFoundException e){
        	Log.e("DBHelper", "Database not existing! Trying to create");
            try {
                db = ctx.createDatabase(DATABASE_NAME, DATABASE_VERSION, 0, null);
                db.execSQL(DATABASE_CREATE);
                return;
            }
            catch(FileNotFoundException e1){
            	Log.e("DBHelper", "Database creation FAILED!!! EXITING!");
                db = null;
                return;
            }
            catch(Exception ex){
            	Log.e("DBHelper", "EVERYTHING FAILED!!! EXITING!");
            	db = null;
            	return;
            }
        }
        catch(Exception ex){
        	Log.e("DBHelper", "EVERYTHING FAILED!!! EXITING!");
        	db = null;
        }
    }

    public void close(){
        db.close();
    }

    public void createRow(String title, String body){
        ContentValues initialValues = new ContentValues();
        initialValues.put("title", title);
        initialValues.put("body", body);
        db.insert(DATABASE_TABLE, null, initialValues);
    }

    public void deleteRow(String title){
        db.delete(DATABASE_TABLE, "title=" + title, null);
    }

    public Hashtable<String, Row> fetchAllRows() {
    	Hashtable<String, Row> ret = new Hashtable<String, Row>();
        try{
            Cursor c = db.query(DATABASE_TABLE, new String[] {"title", "body"},
            		null, null, null, null, null);
            int numRows = c.count();

            Log.v("DBHelper","fetchAllRows numRows: " + numRows);
            
            c.first();
            for (int i = 0; i < numRows; ++i) {
                Row row = new Row();
                row.title = c.getString(0);
                row.body = c.getString(1);
//                Log.v("DBHelper","fetchAllRows putting: title: " + row.title + " body: " + row.body);
                Log.v("DBHelper","fetchAllRows putting: title: " + row.title);
                ret.put(row.title, row);
                c.next();
            }
            Log.v("DBHelper","fetchAllRows Hashtable size: " + ret.size());
        } catch (SQLException e) {
            Log.e("DBHelper", e.toString());
        }
        return ret;
    }
    
    public String[] fetchRowNames(){

        Log.v("DBHelper","fetchRowNames test output");
        
    	Hashtable<String, Row> table = fetchAllRows();
    	
    	String[] retNames = new String[table.size()];
    	Enumeration<String> keyEnum = table.keys();
    	
    	int i = 0;
    	while(keyEnum.hasMoreElements()){
    		retNames[i] = keyEnum.nextElement();
    		i++;
    	
    	}
    	return retNames;
    }

    public Row fetchRow(String title){
    	
    	Log.v("DBHelper", "Fetching row with title: " + title);
    	
    	Row row = new Row();
    	try{
//	        Cursor c = db.query(DATABASE_TABLE, new String[] {"title", "body"},
//	        		"title=" + title, null, null, null, null);
//            Cursor c = db.query(DATABASE_TABLE, new String[]{"title", "body"},
//            		"title", new String[]{title}, null, null, null);
    		Cursor c = db.rawQuery("SELECT title, body FROM " + DATABASE_TABLE +
    				" WHERE title='" + title +"'", null);
//    				new String[]{"title", "body"});
//    		Cursor c = db.query(DATABASE_TABLE, new String[]{"title", "body"}, selection,
//    				selectionArgs, groupBy, having, orderBy);
	        Log.v("DBHelper", "after querying cursor");
	        
	        if(c.count() > 0 && c != null){
	            c.first();
	            row.title = c.getString(0);
	            row.body = c.getString(1);
	            Log.v("DBHelper", "fetched row with title " + row.title);
	            Log.v("DBHelper", "row.body: " + row.body);
	            return row;
	        }
	        else{
	        	Log.v("DBHelper", "FOUND NO ROWS");
	            row.body = row.title = null;
	            row = null;
	        }
    	}
    	catch(Exception ex){
    		Log.e("DBHelper", "fetch Row has a severe problem! title: " + title);
    		Log.e("DBHelper", ex.toString());
    		Log.e("DBHelper", "\n");
    		return null;
    	}
        return row;
    }

    public void updateRow(String title, String body){
    	Row r = null;
		if((r = fetchRow(title)) != null){
	        ContentValues args = new ContentValues();
	        
	        Log.v("DBHelper", "ROW title: " + r.title);
	        Log.v("DBHelper", "ROW body: " + r.body);
	        
	        args.put("title", title);
	        args.put("body", body);
	        Log.v("DBHelper", "updateRow title: " + args.getAsString("title"));
	        Log.v("DBHelper", "updateRow body: " + args.getAsString("body"));
	        
	        //seems that this call has some problem as arguments are not passed
	        //correctly according to logcat output
//	        db.update(DATABASE_TABLE, args, "title=" + title, null);
//	        db.replace(DATABASE_TABLE, null, args);
//	        db.rawQuery("UPDATE " + DATABASE_TABLE + " SET body=" + body +
//	        		" WHERE title=" + title, null);
	        db.execSQL("UPDATE " + DATABASE_TABLE + " SET body='" + body + "' WHERE title='" + title + "'");
		}
		else{
			Log.v("DBHelper", "createRow in update title: " + title);
			Log.v("DBHelper", "createRow in update body: " + body);
			createRow(title, body);
		}
    }
}


